package com.lx.order.listener;

import com.lx.order.entities.UserOrder;
import com.lx.order.mapper.OrderMapper;
import lombok.extern.log4j.Log4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * TODO 添加描述
 *
 * @author wangLJ
 * @date 2024/10/23 22:47
 */

@Component
@RocketMQTransactionListener
public class OrderListener implements RocketMQLocalTransactionListener {

    @Resource
    OrderMapper orderMapper;
    /**
     * 消息发送成功执行 此方法本地事务
     * 事务消息发送成功本方法被回调
     * @param message
     * @param o
     * @return
     */
    @Override
    @Transactional
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        System.out.println("事务消息发送成功,开始指定本地事务");
        UserOrder payload = (UserOrder) message.getPayload();
        orderMapper.insert(payload);
        return RocketMQLocalTransactionState.COMMIT;
    }

    /**
     * 回查事务消息
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        UserOrder payload = (UserOrder) message.getPayload();
        UserOrder userOrder = orderMapper.selectById(payload.getOrderId());
        if (userOrder == null){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        System.out.println("检查本地事务消息"+ payload.toString());

        return RocketMQLocalTransactionState.COMMIT;
    }
}
